package com.example.li_han.servlet;

import com.example.li_han.service.NewsService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
//删除单条新闻
@WebServlet(name = "DeleteNewsById", value = "/DeleteNewsById")
public class DeleteNewsById extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应格式为JSON
        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new Gson();
        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 1. 获取并验证newsId参数
            String newsIdStr = request.getParameter("newsId");
            if (newsIdStr == null || newsIdStr.trim().isEmpty()) {
                resultMap.put("code", 400);
                resultMap.put("msg", "请传入新闻ID（参数名：newsId）");
                response.getWriter().write(gson.toJson(resultMap));
                return;
            }

            // 2. 转换newsId为整数
            int newsId;
            try {
                newsId = Integer.parseInt(newsIdStr.trim());
            } catch (NumberFormatException e) {
                resultMap.put("code", 400);
                resultMap.put("msg", "新闻ID格式错误（必须是整数）");
                response.getWriter().write(gson.toJson(resultMap));
                return;
            }

            // 3. 调用Service层执行删除
            NewsService newsService = new NewsService();
            int result = newsService.deleteNewsById(newsId);

            // 4. 处理删除结果
            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "删除成功（newsId=" + newsId + "）");
            } else {
                resultMap.put("code", 404);
                resultMap.put("msg", "删除失败，新闻ID不存在（newsId=" + newsId + "）");
            }

        } catch (RuntimeException e) {
            // 捕获Service/Dao层抛出的业务异常（如数据库连接失败、SQL错误）
            resultMap.put("code", 500);
            resultMap.put("msg", "删除失败：" + e.getMessage());
            e.printStackTrace(); // 后端打印堆栈，便于调试
        } catch (Exception e) {
            // 捕获其他未预料的异常
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器内部错误：" + e.getClass().getSimpleName());
            e.printStackTrace();
        }

        // 5. 返回响应
        response.getWriter().write(gson.toJson(resultMap));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response); // 支持POST请求
    }
}